package com.losl.framework.web.service;

import com.losl.common.constant.Constant;
import com.losl.common.core.domain.model.LoginUser;
import com.losl.common.core.redis.RedisCache;
import com.losl.common.exception.CustomException;
import com.losl.common.exception.user.CaptchaException;
import com.losl.common.exception.user.CaptchaExpireException;
import com.losl.common.exception.user.PasswordException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 用户登陆处理
 *
 * @author Maxwell
 */
@Component
public class SysUserLoginService {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登陆验证
     */
    public HashMap<String, Object> login(String username, String password, String code, String uuid) {
        String verifykey = Constant.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifykey);
        redisCache.deleteObject(verifykey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        } else if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
        Authentication authentication=null;
        try {
            authentication = manager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new PasswordException();
            } else {
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        HashMap<String, Object> data = new HashMap<>();
        data.put(Constant.TOKEN,tokenService.createToken(loginUser));
        data.put("profile",loginUser.getUser().getProfile());
        return data;
    }

}
